package com.slkj.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.slkj.dto.Name;
import com.slkj.dto.SpecialDutyParam;
import com.slkj.dto.UserinfoDTO;
import com.slkj.entity.Area;
import com.slkj.entity.UserRole;
import com.slkj.entity.Userinfo;
import com.slkj.mapper.AreaMapper;
import com.slkj.mapper.UserMapper;
import com.slkj.mapper.UserRoleMapper;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author admin
 * @version 1.0.0
 * @ClassName UserService.java
 * @Description TODO
 * @createTime 2020年03月06日 20:36:00
 */
@Service
public class UserService {


    private Logger log = LoggerFactory.getLogger(UserService.class);

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private AreaMapper areaMapper;


    public Userinfo findUserinfoByUsername(String username) {

        log.info("---------------------------------------------->>>>>>>> findUserinfoByUsername(String username) 方法");

        Userinfo userinfo = userMapper.selectByUsername(username);
        return userinfo;
    }

    public List<UserRole> getRoleList(int pId) {
        log.info("进入service.getRole(pId)方法");
        List<UserRole> userRoleList1 = userRoleMapper.selectUserRole(pId);
        return userRoleList1;
    }


    public List<UserRole> getRole(int pId) {

        log.info("进入service.getRole(pId)方法");
        List<UserRole> userRoles = new ArrayList<>();
        //获取类型
        List<UserRole> userRoleList1 = userRoleMapper.selectUserRole(pId);
        if (userRoleList1 != null && userRoleList1.size() >= 0) {
            for (UserRole userRole : userRoleList1) {
                userRoles.add(userRole);
            }


            //获取职务/局属
            String idString = userRoleList1.get(0).getId();
            Integer id = Integer.parseInt(idString);
            List<UserRole> userRoleList2 = userRoleMapper.selectUserRole(id);
            userRoleMapper.selectUserRole(id);
            if (userRoleList2 != null && userRoleList2.size() >= 0) {
                for (UserRole userRole : userRoleList2) {
                    userRoles.add(userRole);
                }

                //获取分类/部门
                String id2String = userRoleList2.get(0).getId();
                Integer id2 = Integer.parseInt(id2String);
                List<UserRole> userRoleList3 = userRoleMapper.selectUserRole(id2);
                if (userRoleList3 != null && userRoleList3.size() >= 0) {
                    for (UserRole userRole : userRoleList3) {
                        userRoles.add(userRole);
                    }
                }
            }


        }


        return userRoles;
    }

    /**
     * 增加类型(职务/分类,局属/部分)
     *
     * @throws
     * @title description a
     * @author liamn
     * udateTime a
     */
    public void insertUserRole(UserRole userRole) {
        log.info("进入service.insertUserRole(UserRole userRole)方法,userRole=" + userRole.toString());
        userRoleMapper.insertUserRole(userRole);
    }

    /**
     * 新增用户功能
     *
     * @throws
     * @title description a
     * @author liamn
     * udateTime a
     */
    public void register(String aId, String username, String phone, String roleId, String email) {
        log.info("进入 register(String username, String phone, String roleId, String email)");
        Userinfo userinfo = new Userinfo();
        userinfo.setUsername(username);
        userinfo.setEmail(email);
        userinfo.setRoleId(roleId);
        userinfo.setPhone(phone);
        userinfo.setPassword(new SimpleHash("MD5", "123456", ByteSource.Util.bytes(username), 2).toString());
        userinfo.setPrevLoginTime(new Date());
        userinfo.setaId(aId);


        userMapper.insertUserinfo(userinfo);

        Userinfo findUser = findUserinfoByUsername(username);
        if (findUser == null) {
            log.error("添加用户失败");
            throw new RuntimeException("添加用户失败");
        }
    }

    /**
     * @param userinfo
     * @throwsa
     * @title 修改用户登录时间
     * @description a
     * @author liman
     * @updateTime a
     */
    public void insertPrevLoginTime(Userinfo userinfo) {
        userMapper.updateIsOnlineByUsername(userinfo);
    }

    /**
     * @throwsa
     * @title 登录时修改用户登录状态
     * @description a
     * @author liman
     * @updateTime a
     */
    public void updateIsOnlineByUsername(Userinfo userinfo) {
        log.info("进入 updateIsOnlineByUsername(Userinfo userinfo)");
        userMapper.updateIsOnlineByUsername(userinfo);
    }

    /**
     * @return
     * @throwsa
     * @title 分页查询用户
     * @description a
     * @author liman
     * @updateTime a
     */
    public PageInfo<UserinfoDTO> getUserinfoAll(String search, int gotoPage, int pageSize) {
        log.info("进入List<UserinfoDTO> getUserinfoAll(String search)");

        List<UserinfoDTO> userinfoDTOList = new ArrayList<>();

        List<Map> roleMapList = userRoleMapper.getRoleMap(search);

        Set<String> roleIdSet = new LinkedHashSet<>();
        if (roleMapList != null && roleMapList.size() >= 1) {
            for (Map map : roleMapList) {
                String roleId;
                if (map.containsKey("id")) {
                    roleId = "" + map.get("id");
                } else {
                    roleId = "" + map.get("0id");
                }
                roleIdSet.add(roleId);
            }
        }

        Page<UserinfoDTO> page = PageHelper.startPage(gotoPage, pageSize, true);

        List<UserinfoDTO> userinfoDTOS = userMapper.getUserinfoSearch(roleIdSet, search);
        if (userinfoDTOS != null && userinfoDTOS.size() >= 1) {
            for (UserinfoDTO userinfoDTO : userinfoDTOS) {
                for (Map map : roleMapList) {
                    String roleId;
                    if (map.containsKey("id")) {
                        roleId = "" + map.get("id");
                    } else {
                        roleId = "" + map.get("0id");
                    }
                    if (roleId.equals(userinfoDTO.getRoleId())) {
                        String induty = "" + map.get("行业/部门");
                        String duty = "" + map.get("职务/局属");
                        String type = "" + map.get("类型");
                        String id = "" + map.get("id");
                        if (map.containsKey("id")) {
                            userinfoDTO.setDuty(duty);
                            userinfoDTO.setInduty(induty);
                        }
                        userinfoDTO.setType(type);
                    }


                }
                userinfoDTOList.add(userinfoDTO);
            }
        }


        return new PageInfo<UserinfoDTO>(page.getResult());
    }

    /**
     * @return
     * @throwsa
     * @title 根据userId查询用户(查看功能)
     * @description a
     * @author liman
     * @updateTime a
     */
    public UserinfoDTO getUserinfo(String userId) {
        log.info("UserinfoDTO getUserinfo(String userId)");
        List<Map> roleMapList = userRoleMapper.getRoleMap("");
        UserinfoDTO userinfoDTO = userMapper.getUserinfoByUserId(userId);

        if (userinfoDTO != null && roleMapList != null && roleMapList.size() >= 1) {
            String id = userinfoDTO.getRoleId();
            for (Map map : roleMapList) {
                String roleId;
                if (map.containsKey("id")) {
                    roleId = "" + map.get("id");
                } else {
                    roleId = "" + map.get("0id");
                }
                String induty = "" + map.get("行业/部门");
                String duty = "" + map.get("职务/局属");
                String type = "" + map.get("类型");
                if (roleId.equals(id)) {
                    if (map.containsKey("id")) {
                        userinfoDTO.setDuty(duty);
                        userinfoDTO.setInduty(induty);
                    }
                    userinfoDTO.setType(type);
                }
            }

        }

        String roleId = userinfoDTO.getRoleId();

        //根据id查pid
        int pid = userRoleMapper.selectUserRolePid(Integer.parseInt(roleId));
        //如果pid也就是上层分类id==0,那么这个用户就只有一级分类,没有二三级分类
        String deafultId = "";
        deafultId = roleId;//rouleId就是角色id
        //如果不是那上层就还有一个分类
        if (pid != 0) {
            //再次根据pid查询
            deafultId = deafultId + "-" + pid;
            int pid2 = userRoleMapper.selectUserRolePid(pid);
            if (pid2 != 0) {
                deafultId = deafultId + "-" + pid2;
            }
        }
        String[] split = deafultId.split("-");
        int i = 0;
        for (String s : split) {
            if (i == 0) {
                userinfoDTO.setIndutyId(s);
            } else if (i == 1) {
                userinfoDTO.setDutyId(s);
            } else {
                userinfoDTO.setTypeId(s);
            }
            i++;
        }
        return userinfoDTO;
    }
//
//    /**
//     * @return
//     * @throwsa
//     * @title 根据userId查询用户(编辑功能)
//     * @description a
//     * @author liman
//     * @updateTime a
//     */
//    public UserinfoDTO updateUserinfo(String userId) {
//        log.info("updateUserinfo(String userId) ");
//        UserinfoDTO userinfoDTO = userMapper.selectupdateUserinfoByUserId(userId);
//        List<UserRole> userRoleList = userRoleMapper.selectUserRoleAll();
//
//        if (userinfoDTO != null && userRoleList != null && userRoleList.size() >= 1) {
//            String roleId = userinfoDTO.getRoleId();
//
//            //根据id查pid
//            int pid = userRoleMapper.selectUserRolePid(Integer.parseInt(roleId));
//            //如果pid也就是上层分类id==0,那么这个用户就只有一级分类,没有二三级分类
//            String deafultId = "";
//            deafultId = roleId;//rouleId就是角色id
//            //如果不是那上层就还有一个分类
//            if (pid != 0) {
//                //再次根据pid查询
//                deafultId = deafultId + "-" + pid;
//                int pid2 = userRoleMapper.selectUserRolePid(pid);
//                if (pid2 != 0) {
//                    deafultId = deafultId + "-" + pid2;
//                }
//            }
//            userinfoDTO.setUserRoleList(userRoleList);
//            userinfoDTO.setDeafultId(deafultId);
//        }
//
//        return userinfoDTO;
//
//    }

    /**
     * @throws
     * @title 提交用户编辑功能
     * description a
     * @author liman
     * udateTime a
     */
    public void completeUpdateUserinfo(String userId, String roleId) {
        try {
            userMapper.updateRoleIdByUserId(userId, roleId);
        } catch (Exception e) {
            throw new RuntimeException("修改用户角色失败");
        }
    }


    /**
     * @throws
     * @title 查询所有地区
     * description a
     * @author liman
     * udateTime a
     */
    public List<Area> selectArea() {
        List<Area> areaList = areaMapper.selectAreaAll();
        return areaList;
    }


    /**
     * @throws
     * @title 添加地区
     * description a
     * @author liman
     * udateTime a
     */
    public void insertArea(String areaName) {
        areaMapper.insert(areaName);
    }

    /**
     * @return
     * @throwsa
     * @title 获取领导/专项行动被考核单位
     * @description a
     * @author liman
     * @updateTime a
     */
    public List<Name> getRoleName(String roleName) {
        List<UserRole> userRoleList = userRoleMapper.getRoleByRoleName(roleName);
        if (userRoleList == null) {
            throw new NullPointerException("无数据");
        }
        if (userRoleList.size() == 0) {
            throw new NullPointerException("无数据");

        }
        Set<String> roleIdSet = new LinkedHashSet<>();
        UserRole userRole = userRoleList.get(0);
        roleIdSet.add(userRole.getId());
        List<UserRole> userRoles = userRoleMapper.selectUserRole(Integer.parseInt(userRole.getId()));
        if (userRoles != null && userRoles.size() != 0) {
            for (UserRole role : userRoles) {
                roleIdSet.add(role.getId());
                List<UserRole> earchuserRoles = userRoleMapper.selectUserRole(Integer.parseInt(role.getId()));
                if (earchuserRoles != null && earchuserRoles.size() != 0) {
                    for (UserRole earchuserRole : earchuserRoles) {
                        roleIdSet.add(earchuserRole.getId());
                    }
                }
            }
        }
        List<Name> nameList = userMapper.selectByRoleSet(roleIdSet);
        return nameList;
    }

    public List<UserRole> getRoleAll() {
        List<UserRole> userRoleList = userRoleMapper.selectUserRoleAll();
        return userRoleList;
    }

    public Userinfo getUser(String username) {

        Userinfo userinfo = userMapper.selectByUsername(username);
        return userinfo;
    }
}
